package utils

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
)

func SetAutoStart(enable bool) error {
	switch runtime.GOOS {
	case "darwin":
		return setMacAutoStart(enable)
	// 可以添加其他系统的支持
	default:
		return fmt.Errorf("unsupported operating system")
	}
}

func setMacAutoStart(enable bool) error {
	homeDir, err := os.UserHomeDir()
	if err != nil {
		return err
	}

	launchAgentsDir := filepath.Join(homeDir, "Library", "LaunchAgents")
	plistPath := filepath.Join(launchAgentsDir, "com.clippaste.app.plist")

	if enable {
		// 创建 plist 文件
		plistContent := `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.clippaste.app</string>
    <key>ProgramArguments</key>
    <array>
        <string>` + os.Args[0] + `</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>`

		if err := os.MkdirAll(launchAgentsDir, 0755); err != nil {
			return err
		}

		return os.WriteFile(plistPath, []byte(plistContent), 0644)
	} else {
		// 删除 plist 文件
		return os.Remove(plistPath)
	}
}
